package com.ic.base;

import org.apache.log4j.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * Description:
 * Author: spark
 * Date  : 2017/7/18
 * Time  : 11:49.
 */
public class LoginFilter implements Filter {
	private static final Logger logger = Logger.getLogger(LoginFilter.class);
	private String[] excludedUrls;

	@Override
	public void init(FilterConfig config) throws ServletException {
		String excludes = config.getInitParameter("excludedUrls");
		if (excludes != null) {
			this.excludedUrls = excludes.split(",");
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
						 FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String requestUri = httpRequest.getRequestURI();

		for (String url : excludedUrls) {
			if (requestUri.contains(url.trim())) {
				chain.doFilter(request, response);
				return;
			}
		}
		HttpSession session = httpRequest.getSession(true);
		if (session.getAttribute("userInfo") == null) {
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.html");
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {

	}
}
